//
//  SERegistrationConfirmController.swift
//  SmartEyeForPatient
//
//  Created by qdsg on 2021/4/7.
//

import UIKit

class SERegistrationConfirmController: SEBaseViewController {

    @IBOutlet weak var tableView: UITableView! {
        didSet {
            tableView.tableFooterView = UIView()
            tableView.register(UINib(nibName: SERegistrationConfirmInfoCell.className,
                                     bundle: nil),
                               forCellReuseIdentifier: SERegistrationConfirmInfoCell.reuseId)
            tableView.register(UINib(nibName: SERegistrationConfirmPatientCell.className,
                                     bundle: nil),
                               forCellReuseIdentifier: SERegistrationConfirmPatientCell.reuseId)
            tableView.register(SERegistrationCardListCell.nibForCell(),
                               forCellReuseIdentifier: SERegistrationCardListCell.reuseIdentifier())
            tableView.register(SERegistrationMsgTipCell.nibForCell(),
                               forCellReuseIdentifier: SERegistrationMsgTipCell.reuseIdentifier())
            tableView.register(SEPatientTitleTextFieldCell.nibForCell(),
                               forCellReuseIdentifier: SEPatientTitleTextFieldCell.reuseIdentifier())
            tableView.register(SERegistrationCardCell.nibForCell(),
                               forCellReuseIdentifier: SERegistrationCardCell.reuseIdentifier())
        }
    }


    @IBAction func agreeBtnAction(_ sender: UIButton) {
        sender.isSelected.toggle()
        viewModel.isAgree = sender.isSelected
    }


    @IBOutlet weak var confirmBtnView: SERegistrationConfirmBtnView! {
        didSet {
            confirmBtnView.delegate = self
        }
    }

    var viewModel = SERegistrationConfirmViewModel()

    init(with numItem: SERegistrationNumItem, doctorShift: SERegistrationDoctorShift, needBindCard: Bool, hospitalId: String, hospitalName: String) {
        viewModel.numItem = numItem
        viewModel.doctorShift = doctorShift
        viewModel.needBindCard = needBindCard
        viewModel.hospitalId = hospitalId
        viewModel.hospitalName = hospitalName
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "预约挂号"
    }

    override func setupUI() {
        super.setupUI()
        viewModel.updateData = { [weak self] status in
            switch status {
            case .success:
                self?.pushRegistrationDetailViewController(sourceId: self?.viewModel.sourceId ?? "")
            case .auth:
                self?.presentLoginViewController(selector: #selector(self?.requestNumSubmit))
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

        viewModel.msgCodeHandler = { [weak self] status in
            switch status {
            case .success:
                let cell = self?.tableView.cellForRow(at: IndexPath(row: 1, section: 3)) as! SEPatientTitleTextFieldCell
                cell.fireTimer()
                SEHUD.show(message: "验证码发送成功")
            case .auth(let msg), .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

        viewModel.checkCodeHandler = { [weak self] status in
            switch status {
            case .success:
                break
            case .auth:
                self?.presentLoginViewController(selector: #selector(self?.requestCheckMsgCode))
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

        viewModel.createCardHandler = { [weak self] status in
            switch status {
            case .success:
                self?.tableView.reloadData()
            case .auth:
                self?.presentLoginViewController(selector: #selector(self?.requestCreateCard))
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }
    }

    func pushRegistrationDetailViewController(sourceId: String)  {
        let vc = SERegistrationDetailController(with: sourceId, type: .confirm)
        navigationController?.pushViewController(vc, animated: true)
    }

    func pushPatientListViewController() {
        let patientListType: SEPatientListViewControllerType = viewModel.needBindCard ? .selectNeedCard : .select
        let vc = SEPatientListViewController(with: patientListType,
                                             hospitalId: viewModel.hospitalId)
        vc.selectedHandler = { [weak self] patient in
            self?.viewModel.selectedCardModel = nil
            self?.viewModel.patientListItem = patient
            self?.tableView.reloadData()
        }
        navigationController?.pushViewController(vc, animated: true)
    }

}

// MARK: - UITableViewDataSource,UITableViewDelegate

extension SERegistrationConfirmController: UITableViewDataSource, UITableViewDelegate {

    // MARK: - UITableViewDataSource

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.numberOfRowsInSection(section: section)
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel.numberOfSections
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SERegistrationConfirmInfoCell.reuseId, for: indexPath) as! SERegistrationConfirmInfoCell
            cell.updateCell(numItem: viewModel.numItem, doctorShift: viewModel.doctorShift)
            return cell
        }
        if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SERegistrationConfirmPatientCell.reuseId, for: indexPath) as! SERegistrationConfirmPatientCell
            cell.updateCell(model: viewModel.patientListCellModel)
            return cell
        }
        if indexPath.section == 2 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SERegistrationCardListCell.reuseIdentifier(), for: indexPath) as! SERegistrationCardListCell
            cell.updateCellWithModel(model: viewModel.cardListCellModel(index: indexPath.row))
            return cell
        }
        if indexPath.section == 3 {
            if indexPath.row == 0 {
                let cell = tableView.dequeueReusableCell(withIdentifier: SERegistrationMsgTipCell.reuseIdentifier(), for: indexPath) as! SERegistrationMsgTipCell
                cell.updateCell(viewModel)
                return cell
            }
            if indexPath.row == 1 {
                let cell = tableView.dequeueReusableCell(withIdentifier: SEPatientTitleTextFieldCell.reuseIdentifier(), for: indexPath) as! SEPatientTitleTextFieldCell
                cell.delegate = self
                cell.updateCell(model: SEPatientTitleTextFieldCellModel(title: "验证码", placeHolder: "请输入验证码", cellType: .code, keyboardType: .numberPad, titleFont: UIFont.regular(14)), indexPath: indexPath)
                return cell
            }
        }
        if indexPath.section == 4 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SERegistrationCardCell.reuseIdentifier(), for: indexPath) as! SERegistrationCardCell
            cell.updateCellWithModel(viewModel)
            cell.delegate = self
            return cell
        }
        return UITableViewCell()
    }

    // MARK: - UITableViewDelegate

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        viewModel.heightForRowAt(indexPath: indexPath)
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        viewModel.heightForHeaderInSection(section: section)
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = UIColor.clear
        if section == 2 {
            let label = UILabel(frame: CGRect(x: 15, y: 10, width: UIScreen.screenWidth - 30, height: viewModel.cardMemoStrHeight))
            label.numberOfLines = 0
            label.font = UIFont.regular(12)
            label.textColor = UIColor(hex: "999999")
            label.attributedText = viewModel.cardMemoStr
            view.addSubview(label)
        }
        return view
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 1 {
            pushPatientListViewController()
        }
        if indexPath.section == 2 {
            viewModel.selectedCardModel = viewModel.cardModels[indexPath.row]
            tableView.reloadData()
        }
    }
}

// MARK: - SERegistrationConfirmBtnViewDelegate

extension SERegistrationConfirmController: SERegistrationConfirmBtnViewDelegate {
    func registrationConfirmBtnViewAction(view: SERegistrationConfirmBtnView) {
        if viewModel.cardType == .auth {
            requestCheckMsgCode()
        } else {
            requestNumSubmit()
        }
    }
}


// MARK: - SEPatientTitleTextFieldCellDelegate

extension SERegistrationConfirmController: SEPatientTitleTextFieldCellDelegate {
    func patientTitleTextFieldCellDidEndEdit(titleTextFieldCell: SEPatientTitleTextFieldCell, indexPath: IndexPath) {
        viewModel.msgCode = titleTextFieldCell.textField.text!
    }

    func patientTitleTextFieldCellCodeBtnAction() {
        viewModel.requestMsgCode()
    }

}

// MARK: - SERegistrationCardCellDelegate

extension SERegistrationConfirmController: SERegistrationCardCellDelegate {
    func registrationCardCellCreateBtnAction() {
        SELog("registrationCardCellCreateBtnAction")
        requestCreateCard()
    }
}

// MARK: - APIRequest

extension SERegistrationConfirmController {
    @objc func requestNumSubmit() {
        viewModel.requestNumSubmit()
    }

    @objc func requestCheckMsgCode() {
        viewModel.requestCheckMsgCode()
    }

    @objc func requestCreateCard() {
        viewModel.requestCreateCard()
    }
}
